package cn.exrick.xboot.modules.base.serviceimpl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.exrick.xboot.common.utils.RandomUserInfoUtil;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.exrick.xboot.common.constant.CommonConstant;
import cn.exrick.xboot.common.utils.SecurityUtil;
import cn.exrick.xboot.modules.base.dao.mapper.UserRoleMapper;
import cn.exrick.xboot.modules.base.entity.User;
import cn.exrick.xboot.modules.base.entity.UserRole;
import cn.exrick.xboot.modules.base.enums.RoleEnum;
import cn.exrick.xboot.modules.base.service.UserService;
import cn.exrick.xboot.modules.base.service.WeChatAuthService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

@Service
public class WeChatAuthServiceImpl implements WeChatAuthService {

    @Autowired
    private WxMaService wxMaService;
    @Autowired
    private UserService userService;
    @Autowired
    private SecurityUtil securityUtil;
    @Autowired
    private UserRoleMapper userRoleMapper;


    @Transactional(rollbackFor = Exception.class)
    public String loginWithWeChat(String code) {
        try {
            // 通过code获取openid
            String openid = "";
            if (code.length() <= 6) {
                openid = code;
            }else {
                WxMaJscode2SessionResult sessionInfo = wxMaService.getUserService().getSessionInfo(code);
                openid = sessionInfo.getOpenid();
            }
            // 查询数据库是否存在该用户
            User user = userService.findByOpenId(openid);

            if (user == null) {
                // 如果用户不存在，创建新用户
                user = new User();
                user.setWxOpenid(openid);
                user.setUsername("wechat_user_" + openid); // 设置默认用户名
                // 随即设置nickname
                user.setNickname(RandomUserInfoUtil.generateRandomUsername());
                // 随即设置头像
                user.setAvatar(RandomUserInfoUtil.generateRandomAvatar());
                String encryptPass = new BCryptPasswordEncoder().encode("123456");
                user.setPassword(encryptPass).setType(CommonConstant.USER_TYPE_NORMAL);
                user = userService.save(user);
                if (Objects.isNull(userRoleMapper.selectOne(new LambdaQueryWrapper<UserRole>().eq(UserRole::getUserId, user.getId()).eq(UserRole::getRoleName, RoleEnum.PLATFORM_UER.getValue())))){
                    userRoleMapper.insert(new UserRole().setUserId(user.getId()).setRoleName(RoleEnum.PLATFORM_UER.getValue()));
                }
            }
            // 生成JWT Token
            return securityUtil.getToken("wechat_user_" + openid, false);
        } catch (Exception e) {
            throw new RuntimeException("微信登录失败", e);
        }
    }
}
